<template>
	<view class="order">
        <uv-loading-page :loading="isLoadding" loadingText="生成订单中..." loading-mode="circle"></uv-loading-page>
        <template v-if="!isLoadding">
            <view class="order-header">
                <text>确认订单</text>
                订单超时未支付将自动取消
                <view style="position:absolute;right:32rpx;bottom:-12rpx;color:#fff;">
                    <uv-count-down :time="time" @finish="callback" color="#fff" format="mm:ss"></uv-count-down>
                </view>
            </view>
            <view class="order-info" v-if="Movie.logo && Order.tradeno">
                <view class="order-info-logo" :style="`background-image:url(${Movie.logo})`"></view>
                <view class="order-desc">
                    <view class="name"><text>{{ Movie.name }}</text> {{ Order.quantity }}张</view>
                    <view>{{ Order.description['场次'] }}{{ Order.description['版本'] }}</view>
                    <view>{{ Order.description['影院'] }}</view>
                    <view>{{ Order.description['影厅'] }}</view>
                    <view>{{ Order.description['影票'] }}</view>
                </view>
            </view>
            <view class="order-mobile">
                <view class="order-mobile-iconbox">
                    <uv-icon size="22" name="bell-fill" color="#fff"></uv-icon>
                </view>
                <view class="order-mobile-info">
                    <text>{{ Order.mobile }}</text>
                    购票成功后，会收到取票码短信
                </view>
            </view>

            <view class="yt-list">
                <view class="yt-list-cell coupon-cell" @click="changePay(orderAvailableCoupon,'zeroPay')">
                    <image src="../../static/coupon.svg" mode="widthFix" style="width:32px;margin-right:12px;"/>
                    <text class="cell-tit clamp">兑换券</text>
                    <text  v-if="useCouponArr.length > 0 && payWay != 'zeroPay' && orderAvailableCoupon.length > 0" class="cell-tip disabled">无法使用（储值卡使用中）</text>
                    <template v-else-if="orderAvailableCoupon.length > 0">
                        <text class="available-coupon bg-line-color" v-if="useCouponArr.length > 0">已选{{useCouponArr.length}}张兑换券</text>
                        <text class="available-coupon bg-line-color" v-else>{{orderAvailableCoupon.length}}张可用</text>
                        <uv-icon size="17" name="arrow-right"></uv-icon>
                    </template>
                    <text class="cell-tip disabled" v-else>暂无可用</text>
                </view>
                <!-- <view class="yt-list-cell coupon-cell" @click="changePay(vipCoupon,'vipPay')">
                    <image src="../../static/card.svg" mode="widthFix" style="width:32px;margin-right: 12px;"/>
                    <text class="cell-tit clamp">储值卡</text>
                    <text v-if="useCouponArr.length > 0 && payWay != 'vipPay' && vipCoupon.length > 0" class="cell-tip disabled">无法使用（礼包卡始终中）</text>
                    <template v-else-if="vipCoupon.length > 0">
                        <text class="available-coupon bg-line-color">{{vipCoupon.length}}张可用</text>
                        <uv-icon size="17" name="arrow-right"></uv-icon>
                    </template>
                    <text v-else class="cell-tip disabled">暂无可用</text>
                </view> -->
            </view>

            <view class="order-notice">
                <text>购票须知</text>
                <view>1、请确认所购观赛票场次和时间无误，一旦拼团成功，观赛票将不予退换。                </view>
                <view>2、本次影院观赛采用拼团机制，拼团截止时间为5月17日20时，届时未达成团门槛，将自动取消该观赛场次，所购观赛票款48小时内自动退回。                </view>
                <view>3、出票成功后，将以短信通知，本次观赛采用电子二维码验票，凭小程序内取票码在影院入场口找工作人员核销。</view>
            </view>
            <view class="footer">
                <view class="price-content">
                    <text>实付款</text>
                    <text class="price-tip">￥</text>
                    <text class="price">{{ Order.amount }}</text>
                </view>
                <text class="submit bg-line-color" @click="submit">确认支付</text>
            </view>
        </template>
        <uv-modal ref="dialogRef"
        :closeOnClickOverlay='false'
        :showConfirmButton="true"
        title="信息核对"
        confirmText="确认无误"
        cancelText="重新选择"
        :showCancelButton="true"
        @confirm="dialogRef.close()"
        @cancel="callback"
        >
            <view class="infoBox" v-if="Order.description">
                <view style="background:#f5f5f5;padding:24rpx 18rpx;margin-bottom:16rpx;border-radius: 5px;">
                    <view class="infoBox_item"><text>影片：</text>{{ Order.description['影片'] }}</view>
                    <view class="infoBox_item"><text>影院：</text>{{ Order.description['影院'] }}</view>
                </view>
                <view class="infoBox_item"><text>影厅：</text>{{ Order.description['影厅'] }}</view>
                <view class="infoBox_item"><text>场次：</text><text style="color:red;font-weight: 600;width:auto">{{ Order.description['场次'] }}</text></view>
                <view class="infoBox_item"><text>座位：</text>{{ Order.description['座位价格'] }}</view>
                <view class="infoBox_item"><text>数量：</text>{{ Order.quantity }}</view>
            </view>
        </uv-modal>
        <uv-popup ref="popupRef" round="12" mode="bottom" 
            custom-style="height: 62vh;" 
            bgColor="#f5f5f5" 
            :closeable="true"
            @change="toggleMask"
            closeIconPos="top-right">
            <Coupon :coupons="couponList" :order="Order" :unusedCouponList="unusedCouponList" @useCouponed="pageLoadData" v-if="isCoupon"/>
        </uv-popup>
    </view>
</template>

<script setup lang="ts">
const app = getApp()
import { ref , getCurrentInstance,computed} from 'vue'
import { onLoad } from "@dcloudio/uni-app"
import { getMovieOrder , cancelOrder , getMovieDetail} from "@/api/movie"
import { queryCouponByOrder} from '@/api/coupon'
import { getOrder , setPaymethod} from "@/api/order"
import Coupon from "@/components/coupons"
import { useUCenterStore } from '@/stores/uCenter'
const store = useUCenterStore()
const member = computed(() => {
  return store.memberInfo
})
const isLoadding = ref<any>(true)
const Movie = ref<any>({})
const Order = ref<any>({})
const dialogRef = ref()
const time = ref<any>(15 * 60 * 1000)
const callback = () => {
    cancelOrder({tradeno:Order.value.tradeno}).then(res => {
        uni.navigateBack()
    })
}
const popupRef = ref()
const isCoupon = ref<any>(false)
const toggleMask = (e : any) => {
    isCoupon.value = e.show
}
const submit = () => {
    uni.showLoading()
    setPaymethod({
        paymethod:Order.value.amount > 0?'wxminiPay':payWay.value,
        tradeno:tradeno.value,
        openid:member.value.openid
    }).then(payInfo => {
        uni.hideLoading()
        if(payInfo.success){
            const info = payInfo.data
            if(info){
                uni.requestPayment({
                    "provider": "wxpay",
                    ...info,
                    success(res) {
                        uni.redirectTo({url:'/pages/movie/paySuccess'})
                    },
                    fail(e) {
                        uni.showToast({title:payInfo.msg,icon:'none'})
                    }
                })
            }else{
                uni.redirectTo({url:'/pages/movie/paySuccess'})
            }
        }else{
            uni.showToast({title:payInfo.msg,icon:'none'})
        }
    }).catch(res => {
        uni.showLoading()
    })
}
const couponList = ref<any>([]) //选择礼包卡或者储值卡支付时，需要项组件提交的数据
const tradeno = ref<any>() 
const payWay = ref<any>('wxminiPay') //支付方式
const vipCoupon = ref<any>([]) //储值卡
const useCouponArr = ref<any>([]) //已使用的卡
const orderAvailableCoupon = ref<any>([]) //礼包卡
const unusedCouponList = ref<any>([])
const getOrderCoupon = () => {
    queryCouponByOrder({ tradeno: tradeno.value }).then((res) => {
        orderAvailableCoupon.value = []//礼包卡
        vipCoupon.value = []//储值卡
        couponList.value = []
        useCouponArr.value = []//缓存已经选择使用的卡
        res.data && res.data.couponList.forEach(item => {
            if(item.type == "A"){
                orderAvailableCoupon.value.push(item)
            }else if(item.type == "VIP"){
                vipCoupon.value.push(item)
            }
            if(item.isUse){
                useCouponArr.value.push(item)
                payWay.value = (item.type == "A"?'zeroPay':'vipPay')
            }
        })
        unusedCouponList.value = res.data.unusedCouponList
        initCoupons()
    })
}
const initCoupons = () => {
    couponList.value = []
    if(payWay.value == "zeroPay")couponList.value = orderAvailableCoupon.value
    if(payWay.value == "vipPay")couponList.value = vipCoupon.value
}
const changePay = (arr : any,way : any) => {
    const text = way == 'zeroPay'?'礼包卡':'储值卡'
    if(arr.length == 0 && unusedCouponList.value.length == 0){
        uni.showToast({title:`暂无${text}可用`,icon:'none'})
        return
    }
    if(useCouponArr.value.length > 0 && payWay.value != way){
        uni.showToast({title:`礼包卡与储值卡不能同时使用`,icon:'none'})
        return
    }
    payWay.value = way
    couponList.value = arr
    popupRef.value.open()
}

const pageLoadData = (evcallback : any) => {
    getMovieOrder({tradeno:tradeno.value}).then(res => {
        Order.value = res.data
        if(res.data.amount == 0)popupRef.value.close()
        isLoadding.value = false
        const ctime = new Date(res.data.expireTime).getTime() - new Date().getTime()
        time.value = ctime
        if(evcallback && typeof evcallback == 'function')evcallback()
    })
    getOrderCoupon()
}

onLoad(async (options : any) => {
	const { proxy } = getCurrentInstance();
	await proxy.$onLaunched;
    tradeno.value = options.tradeno
    Movie.value = uni.getStorageSync('Movie')
    if(options.movieId){
        getMovieDetail({id : options.movieId}).then(res => {
            Movie.value = res.data
        })
    }
    pageLoadData(() => {
        dialogRef.value.open()
    })
})
</script>
<style lang="scss">
.order{
    padding-bottom:7vh;
    .uv-count-down__text{
        color:#fff !important;
    }
}
.order-header{
    padding:32upx 32upx 0;
    position: relative;
    color:#fff;
    font-size:28upx;
    display:flex;
    flex-direction: column;
    text{
        font-size:36upx;
        font-weight: 600;
        margin-bottom:12upx;
    }
}
.yt-list ,.order-info , .order-mobile,.order-notice{
    background: #fff;
    margin:32upx;
    border-radius: 9px;
    font-size: $font-base;
    box-shadow:0 0 3px rgba(0,0,0,.1);
}
.order-info{
    display:flex;
    padding:32upx;
    line-height: 1.5;
    .order-info-logo{
        width:22vw;
        height:32vw;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        margin-right:22upx;
    }
    .name{
        color:rgba(173, 46, 62,1);
        margin-bottom:12upx;
        text{
            font-size: 36upx;
            font-weight: 600;
            color:#000;
            margin-right:22upx;
        }
    }
}
.order-mobile{
    display:flex;
    padding:32upx;
    line-height: 1.5;
    .order-mobile-info{
        display:flex;
        flex-direction: column;
        text{
            font-size:36upx;
            font-weight: 600;
            color:#000;
        }
    }
    .order-mobile-iconbox{
        width:32px;
        height:32px;
        border-radius:32px;
        background:#666;
        color:#fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right:12px;
    }
}
.order-notice{
    display:flex;
    flex-direction: column;
    padding:32upx;
    line-height: 1.5;
    text{
        border-bottom: 1px solid #eee;
        font-size:32upx;
        margin-bottom:22upx;
        padding-bottom:22upx;
    }
}
.yt-list-cell {
    display: flex;
    align-items: center;
    padding: 10upx 30upx 10upx 40upx;
    line-height: 70upx;
    position: relative;

    &.cell-hover {
        background: #fafafa;
    }

    &.b-b:after {
        left: 30upx;
    }

    .cell-icon {
        text-align: center;
        border-radius: 4upx;
        margin-right: 12upx;
    }

    .cell-more {
        align-self: center;
        font-size: 24upx;
        color: $font-color-light;
        margin-left: 8upx;
        margin-right: -10upx;
    }

    .cell-tit {
        flex: 1;
        color: $font-color-dark;
        margin-right: 10upx;
        font-weight: 600;
    }

    .cell-tip {
        font-size: 26upx;
        color: $font-color-dark;
        
        &.disabled {
            color: $font-color-light;
        }

        &.active {
            color: $base-color;
        }
        &.red{
            color: $base-color;
        }
    }

    &.desc-cell {
        .cell-tit {
            max-width: 90upx;
        }
    }

    .desc {
        flex: 1;
        font-size: $font-base;
        color: $font-color-dark;
    }
}
.coupon-cell{
    padding:32upx 32upx 32upx 40upx;
    position: relative;
    &::after{
        position: absolute;
        content: "";
        width: 90%;
        height: 1px;
        background-color: rgba(0, 0, 0, 0.05);
        right: 5%;
        bottom: 0;
    }
    &:last-child::after{height:0;}
    .available-coupon {
        border-radius: 32px;
        background: linear-gradient(to right, #ff9565, #fb2c4c);
        color: #fff;
        padding: 6upx 22upx;
        font-size: $font-base;
        height: 32upx;
        line-height: 32upx;
    }
}
.footer{
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 995;
    display: flex;
    align-items: center;
    width: 100%;
    height: 90upx;
    justify-content: space-between;
    font-size: 30upx;
    background-color: #fff;
    z-index: 998;
    color: $font-color-base;
    box-shadow: 0 -1px 5px rgba(0,0,0,.1);
    .price-content{
        padding-left: 30upx;
    }
    .price-tip{
        color: $base-color;
        margin-left: 8upx;
    }
    .price{
        font-size: 36upx;
        color: $base-color;
    }
    .submit{
        display:flex;
        align-items:center;
        justify-content: center;
        width: 280upx;
        height: 100%;
        color: #fff;
        font-size: 32upx;
        background-color: $base-color;
    }
}
.infoBox{
    padding:32rpx 0;
    background:#fff;
    .infoBox_item{
        line-height: 1.5;
        display:flex;
        text{
            width:106rpx;
            color:#999;
        }
    }
}
</style>